package com.cskaoyan.aspect;

import com.cskaoyan.service.LogService;
import com.cskaoyan.vo.BaseRespVo;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;


/**
 * 作者：grz
 * 功能：日志记录AOP
 */

@Aspect
@Component
public class LogAspect {

    @Autowired
    LogService logService;


    // 定义切点Pointcut
    @Pointcut("execution(* com.cskaoyan.controller.*Controller.*(..))")
    public void logService() {
    }

    @Around("logService()")
    public Object doAround(ProceedingJoinPoint pjp) throws Throwable {

        //System.out.println("LOG记录...");

        RequestAttributes ra = RequestContextHolder.getRequestAttributes();
        if (ra == null) {
            throw new RuntimeException("LogAspect获取request失败");
        }

        ServletRequestAttributes sra = (ServletRequestAttributes) ra;
        HttpServletRequest request = sra.getRequest();
        BaseRespVo result = (BaseRespVo) pjp.proceed();

        logService.logCreate(request, result);
        return result;
    }
}
